﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;

namespace JshRCSWebApi.Util.Transition
{
    public class ModelHelper
    {
        #region dataTable 转为实体
        public static List<T> TableToList<T>(DataTable dt) where T : class, new()
        {
            Type type = typeof(T);
            List<T> list = new List<T>();
            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    PropertyInfo[] properties = type.GetProperties();
                    T model = new T();
                    foreach (PropertyInfo p in properties)
                    {
                        if (row.Table.Columns.Contains(p.Name))
                        {
                            object value = row[p.Name];
                            value = Convert.ChangeType(value, p.PropertyType);
                            if (value != DBNull.Value)
                                p.SetValue(model, value, null);
                        }
                    }
                    list.Add(model);
                }
                return list;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        #endregion

    }
}